package com.youlu.campus.service.university;

import com.youlu.campus.entity.MajorInfo;
import com.youlu.campus.entity.VO.req.ImportExcelMajorInfoVO;
import com.youlu.campus.entity.VO.req.MajorQueryReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class MajorInfoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public void saveBatch(List<ImportExcelMajorInfoVO> excelDataList){
        List<MajorInfo> majorInfoList = excelDataList.parallelStream().map(excelData -> {
            MajorInfo majorInfo = new MajorInfo();
            majorInfo.setName(excelData.getName());
            return majorInfo;
        }).collect(Collectors.toList());
        this.mongoTemplate.insertAll(majorInfoList);
    }

    public List<MajorInfo> list(MajorQueryReq majorQueryReq){
        String majorName = majorQueryReq.getName();
        if(StringUtils.isBlank(majorName)){
            return new ArrayList<>();
        }
        Query query = new Query();
        Pattern pattern = Pattern.compile("^.*" + majorName + ".*$", Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("name").regex(pattern));
        query.limit(10);
      return this.mongoTemplate.find(query,MajorInfo.class);
    }
}
